﻿namespace System.Threading
{
    public static class ReaderWriterLockEx
    {
        public static void Reader(this ReaderWriterLock _lock, Action action)
        {
            _lock.AcquireReaderLock(Timeout.Infinite);
            try
            {
                action?.Invoke();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
            _lock.ReleaseReaderLock();
        }

        public static T Reader<T>(this ReaderWriterLock _lock, Func<T> action)
        {
            T t = default(T);
            _lock.AcquireReaderLock(Timeout.Infinite);

            try
            {
                if (action != null)
                    t = action.Invoke();
            }
            catch
            {

            }

            _lock.ReleaseReaderLock();
            return t;
        }

        public static void Write(this ReaderWriterLock _lock, Action action)
        {
            _lock.AcquireWriterLock(Timeout.Infinite);
            try { action?.Invoke(); } catch { }
            _lock.ReleaseWriterLock();
        }
    }
}
